<script lang="ts" setup>
import { ref } from "vue";
import { getAddress } from "~/api/public";
import { useMapData } from "~/api/map";
import { Snackbar } from "@varlet/ui";

const mapDom = ref<HTMLElement | null>(null);
const { data: MapData } = await useMapData();
const startPoint = ref(getCenterByName());
const endPoint = ref(getCenterByName("江西"));

function getCenterByName(name = "争议", light = 0) {
  if (!mapDom.value)
    return {
      x: 0,
      y: 0,
    };
  const map = mapDom.value;
  // 找出id里包含name的元素
  const target = map.querySelector(`[id*="${name}"]`);
  if (target) {
    // 获取元素的中心点
    const { x, y, width, height } = target.getBoundingClientRect();
    const mapRect = map.getBoundingClientRect();
    if (light) target.setAttribute("fill", getColorByValue(light));
    return {
      x: x + width / 2 - mapRect.x,
      y: y + height / 2 - mapRect.y,
    };
  }
  return getCenterByName("争议", light);
}

function getColorByValue(value: number) {
  if (value < 1) return "#3a7afe11";
  if (value < 10) return "#3a7afe33";
  if (value < 50) return "#3a7afe55";
  if (value < 100) return "#3a7afe77";
  if (value < 200) return "#3a7afe99";
  if (value < 1000) return "#3a7afeAA";
  return "#3a7afe";
}

onMounted(() => {
  getAddress().then((res) => {
    const { region } = res;
    if (!region) return;
    Snackbar.info(`欢迎你，来自${region}的朋友!`);
    startPoint.value = getCenterByName(region);
    if (region.includes("江西")) {
      endPoint.value = getCenterByName("上海");
    }
  });
  const { data } = MapData.value ?? {};
  if (Array.isArray(data)) {
    data.forEach((item) => {
      const { name, value } = item;
      const target = mapDom.value?.querySelector(`[id*="${name}"]`);
      if (target) target.setAttribute("fill", getColorByValue(value));
    });
  }
});
</script>

<template>
  <div
    class="homeMapBody"
    ref="mapDom"
  >
    <!-- 创建一条贝塞尔svg曲线，从起始点到终点 -->
    <svg
      v-if="startPoint.x && endPoint.x"
      width="100%"
      height="100%"
      class="line"
      xmlns:xlink="http://www.w3.org/1999/xlink"
    >
      <path
        :d="`M${startPoint.x},${startPoint.y} Q${startPoint.x},${endPoint.y} ${endPoint.x},${endPoint.y}`"
        stroke="#3a7afe"
        fill="none"
        stroke-width="2"
        stroke-linecap="round"
        id="motionPath"
      ></path>
      <circle
        cx="0"
        cy="0"
        r="4"
        fill="#3a7afe"
      >
        <animateMotion
          dur="6s"
          repeatCount="indefinite"
        >
          <mpath xlink:href="#motionPath" />
        </animateMotion>
      </circle>
    </svg>
    <CountryMap></CountryMap>
  </div>
</template>

<style lang="less" scoped>
.homeMapBody {
  display: grid;
  place-items: center;
  height: 100%;
  width: 100%;
  position: relative;
  .line {
    position: absolute;
    z-index: 1;
    pointer-events: none;
  }
}
</style>
